// Prevents additional console window on Windows in release, DO NOT REMOVE!!
//#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]

use anyhow;
use dirs::*;

pub use hello_lib::{shared::{Shared, Config}, chatdb::* };

use std::{string::String, sync::Arc};
use tauri::Manager;
use time::{format_description, UtcOffset};
use tokio;
use tokio::sync::{broadcast, broadcast::Receiver, mpsc};
use tracing::{debug, error, info};
use tracing_subscriber::{
    self, filter::EnvFilter, fmt, fmt::time::OffsetTime, layer::SubscriberExt,
    util::SubscriberInitExt, Registry,
};
use std::path::PathBuf;
type Result<T> = anyhow::Result<T>;



#[tokio::main]
async fn main() -> Result<()> {
    tracelog_init("debug");

    let home_dir = dirs::home_dir().unwrap();
    //let home_dir = tauri::AppHandle::path().home_dir().unwrap();    
    let appconfig = home_dir.join("yeeapp").join("yeeapp.json");
    if !appconfig.exists() {
        std::fs::create_dir_all(appconfig.parent().unwrap()).unwrap();
        let default_cfg = include_str!("../conf/yeeapp.json");
        std::fs::write(appconfig, default_cfg).unwrap();
        error!("请先配置 {}/yeeapp/yeeapp.json", home_dir.display());
    }
    
    let cfg_file = format!("{}", home_dir.join("yeeapp").join("yeeapp.json").display());

     let dbpath = home_dir.join("yeeapp").join("db");
     if dbpath.exists() == false {
          std::fs::create_dir_all(&dbpath).unwrap();
     }
     let database_name = format!("sqlite:{}{}hello.db", dbpath.display(), std::path::MAIN_SEPARATOR);
     let dbpool = create_db_pool(&database_name).await?;

    let shared = Shared::new(&cfg_file, dbpool);
    let shared: Arc<Shared> = Arc::new(shared);
    // 此处阻塞！直到hello_lib退出
    hello_lib::run(shared);

    return Ok(());
}

fn tracelog_init(trace_level: &str) {
    // debug!("当前采用tracing的rolling log模式, 可修改Cargo.toml, 改为基于log4rs的log模式");
    let secs = chrono::Local::now().offset().local_minus_utc();
    let offset = UtcOffset::from_whole_seconds(secs).unwrap();

    let env_filter =
        EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new(trace_level));
    let format = "[year]-[month]-[day] [hour]:[minute]:[second].[subsecond digits:3]";
    // 写入控制台 stderr
    let formatting_layer = fmt::layer()
        .pretty()
        .with_writer(std::io::stderr)
        .with_timer(OffsetTime::new(
            offset,
            format_description::parse(format).unwrap(),
        ));
    // 注册
    Registry::default()
        .with(env_filter)
        .with(formatting_layer)
        .init();
}
